package server;


import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.stream.ChunkedWriteHandler;


/**
 * Created by xuweijie on 2017/6/17.
 */
public class WebsocketChatServerInitializer extends ChannelInitializer<Channel> {

    /**
     * 添加 ChannelHandler　到 ChannelPipelineinitChannel() 方法设置 ChannelPipeline 中所有新注册的 Channel,安装所有需要的　 ChannelHandler
     * @param channel
     * @throws Exception
     */
    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast("http-codec",new HttpServerCodec());
        pipeline.addLast("aggregator",new HttpObjectAggregator(64*1024));
        pipeline.addLast("http-chunked",new ChunkedWriteHandler());// WebSocket通信支持
        pipeline.addLast("handler",new WebsocketChatServerHandler());
        pipeline.addLast(new StringDecoder());//将消息转成字符串
        pipeline.addLast(new LineBasedFrameDecoder(64*1024));//以换行为标志的解码
    }

}
